package com.diligent.cloud.sfc.config;

import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * ThreadPoolConfig class
 *
 * @author xf107278
 * @date 6/15/2020
 */
@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor threadPool()  {
        //最大可用的CPU核数
        int PROCESSORS = Runtime.getRuntime().availableProcessors();
        //线程最大的空闲存活时间，单位为秒
        int KEEPALIVETIME = 60;
        //任务缓存队列长度
        int BLOCKINGQUEUE_LENGTH = 500;
        ThreadPoolExecutor executor = new ThreadPoolExecutor(PROCESSORS * 2, PROCESSORS * 4, KEEPALIVETIME,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(BLOCKINGQUEUE_LENGTH));

        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//        final CountDownLatch countDownLatch=new CountDownLatch(maps.size());
//
//        for (int i = 0; i < maps.size(); i++) {
//            WoOrder order = JSON.parseObject(JSON.toJSONString(maps.get(i)), WoOrder.class);
//
//            executor.execute(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        test1(order, answer);
//                        Thread.sleep(500);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }finally {
//                        countDownLatch.countDown();
////                                         System.out.println("线程池中线程数目：" + executor.getPoolSize() +
////                                                 "，队列中等待执行的任务数目：" + executor.getQueue().size() +
////                                                 "，已执行完毕的任务数目：" + executor.getCompletedTaskCount());
//                    }
//                }
//            });
//        }
//        try {
//            //等待子线程全部结束
//            countDownLatch.await();
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return executor;
    }
}
